package com.price.httplib

import com.price.common.util.JsonUtils
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okio.Buffer
import java.io.File
import java.nio.charset.Charset

object RetrofitUtil {

    /**
     * String转RequestBody String、ByteArray、ByteString都可以用toRequestBody()
     * */
    fun convertToRequestBody(bean: Any?): RequestBody {
        val json: String = JsonUtils.toJson(bean)
        return json.toRequestBody("application/json;charset=utf-8".toMediaType())
    }
    /**
     * 将String 字符串转换为Rrtorfit: requestBody类型的value
     */
    fun convertToRequestBody(param: String?): RequestBody {
        return param!!.toRequestBody("application/json;charset=utf-8".toMediaType())
    }

    /**
     * File转RequestBody
     * */
    fun convertFileList(file: File): MultipartBody.Part{
//        val file=File("")
        val requestBody= file.asRequestBody("text/x-markdown; charset=utf-8".toMediaType())
        return MultipartBody.Part.createFormData("file", file.name, requestBody)
    }

    /**
     * File转RequestBody
     * */
    fun convertFileList(file: File,requestBody:RequestBody): MultipartBody.Part{
//        val file=File("")

        return MultipartBody.Part.createFormData("file", file.name, requestBody)
    }

    fun convertFileList(fileList: List<File>): List<MultipartBody.Part> {
        return fileList.map { file ->
            MultipartBody.Part.createFormData("file", file.name,
                file.asRequestBody("application/octet-stream".toMediaTypeOrNull())
            )
        }
    }
    //获取RequestBody中的参数
    fun getRequestBody (body:RequestBody):String{
        val buffer = Buffer()
        body.writeTo(buffer)

        //编码设为UTF-8
        var charset = Charset.forName("UTF-8")
        val contentType = body.contentType()
        if (contentType != null) {
            charset = contentType.charset(Charset.forName("UTF-8"))
        }
        //拿到request
        return buffer.readString(charset);
    }
}